package pers.qianyu.month_202101.date_20210117;

import pers.qianyu.util.model.*;

/**
 * 148. 排序链表
 * https://leetcode-cn.com/problems/sort-list/
 *
 * @author mizzle rain
 * @date 2021-01-17 17:35
 */
public class SortList {
    public ListNode sortList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode fast = head.next, slow = head;
        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }
        ListNode temp = slow.next;
        slow.next = null;
        ListNode left = sortList(head);
        ListNode right = sortList(temp);
        ListNode root = new ListNode(), p = root;
        while (left != null && right != null) {
            if (left.val > right.val) {
                p.next = right;
                right = right.next;
            } else {
                p.next = left;
                left = left.next;
            }
            p = p.next;
            p.next = null;
        }
        if (left != null) p.next = left;
        if (right != null) p.next = right;
        return root.next;
    }
}
